//
//  AddadressViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/17.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "AddadressViewController.h"

@interface AddadressViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UIScrollViewDelegate>{
    NSString *provice;
    NSString *state;
    NSString *area;
}
@property(nonatomic,strong)UIPickerView *pickerView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)NSMutableArray *cities;
@property(nonatomic,strong)NSMutableArray *areas;
@property(nonatomic,strong)NSMutableArray *streets;
@property(assign)NSInteger selectIdnex;
@property(assign)NSInteger selectAreaIndex;
@property(assign)NSInteger firstIndex;
@property(assign)NSInteger secondIndex;
@property(assign)NSInteger thirdIndex;
@property(assign)NSInteger fourthIndex;
@property(assign)BOOL selelct;
@end

@implementation AddadressViewController
-(UIPickerView *)pickerView{
    if(!_pickerView){
       _pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, screen_height-216, screen_width, 216)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        [self.view addSubview:_pickerView];
        [self.view bringSubviewToFront:_pickerView];
        _pickerView.hidden = 1;
    }
    return _pickerView;
}
-(NSMutableArray *)dataSource{
    if(!_dataSource){
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
-(NSMutableArray *)cities{
    if(!_cities){
        _cities = [NSMutableArray array];
    }
    return _cities;
}
-(NSMutableArray *)areas{
    if(!_areas){
        _areas = [NSMutableArray array];
    }
    return _areas;
}
-(NSMutableArray *)streets{
    if(!_streets){
        _streets = [NSMutableArray array];
    }
    return _streets;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     [self setNavigation:1 andTitle:@"新建收货地址" andNaviColor:[UIColor clearColor] andTitleColor:nil];
    [self getRegion:@"1" andpid:@"0"];
    self.addressId = @"";
    self.botomScroView.contentSize = CGSizeMake(0, screen_height*1.2);
    self.botomScroView.delegate = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKb)];
    [self.view addGestureRecognizer:tap];
    if(self.AddressDic){
        [self setValue];
    }
    [self.defaultSwith addTarget:self action:@selector(defalult:) forControlEvents:UIControlEventValueChanged];
    // Do any additional setup after loading the view from its nib.
}
-(void)defalult:(UISwitch *)swith{
    if(self.AddressDic){
            NSDictionary *paramter = @{@"op":@"address",@"ctrl":@"live",@"ac":@"member",@"ta":@"address_default",@"id":self.addressId};
            [self weqPostHandle:paramter success:^(id response) {
                if(response){
                    [WToast showWithText:@"设置成功"];
                }
            } failure:^(NSError *error) {
                
            }];
 
    }else{
        [WToast showWithText:@"请先添加地址后在编辑"];
    }
}
-(void)setValue{
    self.name_Tf.text = self.AddressDic[@"name"];
    self.contct_Tf.text = self.AddressDic[@"mobile"];
    self.address_Tf.text = self.AddressDic[@"address"];
    self.city_Lab.text = [NSString stringWithFormat:@"%@%@%@",self.AddressDic[@"province_cn"],self.AddressDic[@"city_cn"],self.AddressDic[@"area_cn"]];
    self.defaultSwith.on = [self.AddressDic[@"is_default"]boolValue];
    self.addressId = self.AddressDic[@"id"];
    //if([self.AddressDic[@"is_default"]boolValue]==1)
    
}
-(void)hideKb{
    [self.view endEditing:1];
}

-(void)loadCity{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)selectCity:(UIButton *)sender {
    self.pickerView.hidden = !self.pickerView.hidden;
}
- (IBAction)saveAddress:(Regular_Btn *)sender {
    [self.view endEditing:1];
    self.pickerView.hidden = 1;
    NSString *name = self.name_Tf.text;
    NSString *mobile = self.contct_Tf.text;
    NSString *detailAdd = self.address_Tf.text;
    if(name&&mobile&&detailAdd){
    }else{
        [WToast showWithText:@"请填写完整的信息"];
    }
    NSString *proId;
    NSString *cityId;
    NSString *districtId;
    if(!self.addressId){
        if(self.selelct!=1){
            [WToast showWithText:@"请选择地区"];
            return;
        }
    }
     proId = [self.dataSource objectAtIndex:self.firstIndex][@"id"];
    cityId = [self.cities objectAtIndex:self.secondIndex][@"id"];
    districtId = [self.areas objectAtIndex:self.thirdIndex][@"id"];
    if(self.AddressDic&&self.selelct==0){
        proId = self.AddressDic[@"province"];
        cityId = self.AddressDic[@"city"];
        districtId = self.AddressDic[@"area"];
    }
    if(self.AddressDic){
        self.addressId = self.AddressDic[@"id"];
    }
    NSDictionary *paramter = @{@"op":@"address",@"ctrl":@"live",@"ac":@"member",@"ta":@"post_address",@"name":self.name_Tf.text,@"mobile":self.contct_Tf.text,@"address":self.address_Tf.text,@"province":proId,@"city":cityId,@"area":districtId,@"id":self.addressId};
    [self weqPostHandle:paramter success:^(id response) {
        if(response){
            [WToast showWithText:@"添加成功"];
            [self.navigationController popViewControllerAnimated:1];
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.pickerView.hidden = 1;
}
-(void)getRegion:(NSString *)level andpid:(NSString *)pid
{
    
    
    //self.selelct = 1;
    NSDictionary *paramter = @{@"op":@"activity",@"ctrl":@"live",@"ac":@"store",@"ta":@"city",@"level":level,@"id":pid};
    [self weqPostHandle:paramter success:^(id response) {
        if(response){
            if([level isEqualToString:@"2"])[self.cities removeAllObjects];
            if([level isEqualToString:@"3"])[self.areas removeAllObjects];
            for(NSDictionary *dic in [response objectForKey:@"data"])
            {
                if([level isEqualToString:@"1"]){
                  
                    [self.dataSource addObject:dic];
                    
                }
                else if ([level isEqualToString:@"2"])
                {
                    
                   
                    [self.cities addObject:dic];
                   
                }
                else
                {
                    
                    [self.areas addObject:dic];
                    
                }
                
            }
            if([level isEqualToString:@"1"])
            {[self.pickerView reloadComponent:0];
                [self reloadfirstCommpents];
                self.firstIndex = 0;
                [self.pickerView selectRow:0 inComponent:0 animated:YES];
            }
            else if ( [level isEqualToString:@"2"])
            {
                [self.pickerView reloadComponent:1];
                self.secondIndex = 0;
                [self reloadsecodCommpents];
                [self.pickerView selectRow:0 inComponent:1 animated:YES];
            }
            else
            {
                self.thirdIndex = 0;
                [self.pickerView reloadComponent:2];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)reloadfirstCommpents
{
    NSString *pid = [NSString stringWithFormat:@"%@",self.dataSource[0][@"id"]];
    [self getRegion:@"2" andpid:pid];
    self.secondIndex = 0;
    
}
-(void)reloadsecodCommpents
{
    NSString *pid = [NSString stringWithFormat:@"%@",self.cities[0][@"id"]];
    [self getRegion:@"3" andpid:pid];
    self.thirdIndex = 0;
    
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    if(component==0)
    {
        return self.dataSource.count;
    }
    else if (component==1)
    {
        return self.cities.count;
    }
    else
    {
        return self.areas.count;
    }

    
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title;
    if(component==0)
    {
        title = [self.dataSource[row]objectForKey:@"name"];
        provice = title;
    }else if (component==1)
    {
        title = [[self.cities objectAtIndex:row]objectForKey:@"name"];
        state = title;
    }
    else if(component==2)
    {
        title = [[self.areas objectAtIndex:row]objectForKey:@"name"];
        if(self.areas.count>0)
        {
            area = title;
        }
        
    }else
    {
    
    }
    NSString *address;
    if(self.areas.count>0)
    {
        address= [NSString stringWithFormat:@"%@%@%@",provice,state,area];
    }
    else
    {
        address = [NSString stringWithFormat:@"%@%@",provice,state];
    }
    if(self.selelct)
    {
        self.city_Lab.text = address;
    }
   return title;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   
    self.selelct = 1;
    if(component==0)
    {
        self.firstIndex = row;
        //  [self.cities removeAllObjects];
        [pickerView selectRow:0 inComponent:1 animated:YES];//更新到第一行
        NSString *pid = [self.dataSource objectAtIndex:row][@"id"];
        [self getRegion:@"2" andpid:pid];

    }
    else if(component==1)
    {
        self.secondIndex = row;
[pickerView selectRow:0 inComponent:2 animated:YES];//更新到第一行
        NSString *pid = [self.cities objectAtIndex:row][@"id"];
        [self getRegion:@"3" andpid:pid];
        }
    else     {
        self.thirdIndex = row;
        [self.streets removeAllObjects];
        NSString *pid = [self.areas objectAtIndex:row][@"id"];
        [self getRegion:@"4" andpid:pid];
    }
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 30;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.view endEditing:1];
    self.pickerView.hidden = 1;
}
-(void)textViewDidBeginEditing:(UITextView *)textView
{
  //  self.placeLb.hidden = 1;
    self.pickerView.hidden = 1;
}
-(void)textViewDidChange:(UITextView *)textView
{
    //NSLog(@"....%lu",(unsigned long)textView.text.length);
    NSLog(@"......%lu",(unsigned long)textView.text.length);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (IBAction)showPicker:(UIButton *)sender {
    [self.view endEditing:1];
   // [self.scroView setContentOffset:CGPointMake(0, 100) animated:YES];
    self.pickerView.hidden = !self.pickerView.hidden;
}
//确认添加
- (IBAction)DoConfirm:(UIButton *)sender {
    [self.view endEditing:1];
    self.pickerView.hidden = 1;
    NSString *name = self.name_Tf.text;
    NSString *mobile = self.contct_Tf.text;
    NSString *detailAdd = self.address_Tf.text;
    if(name&&mobile&&detailAdd){
        
    }else{
        [WToast showWithText:@"请填写完整的信息"];
    }
    NSDictionary *paramter = @{@"op":@"address",@"ctrl":@"live",@"ac":@"member",@"ta":@"post_address",@"id":self.addressId};
    //    if(self.addressDic)
    //    {
    //
    //    }
//    if(self.addressDic)
//    {
//
//        if([self.nameTf.text isEqualToString:self.addressDic[@"consignee"]]&&[self.numTf.text isEqualToString:self.addressDic[@"mobile"]]&&[self.addressLb.text isEqualToString:[NSString stringWithFormat:@"%@%@%@",self.addressDic[@"province"],self.addressDic[@"city"],self.addressDic[@"district"]]]&&[self.DetailText.text isEqualToString:self.addressDic[@"address"]])
//        {
//            [WToast showWithText:@"至少更改一项信息"];
//            return;
//        }
//    }else
//    {
//        if([self.nameTf.text isEqualToString:@""]||[self.numTf.text isEqualToString:@""]||[self.addressLb.text isEqualToString:@""]||[self.DetailText.text isEqualToString:@""]||self.firstIndex<0||self.secondIndex<0||self.thirdIndex<0)
//        {
//            [WToast showWithText:@"请填写完整的收货信息"];
//            return;
//        }
//    }
    NSString *proId;
    NSString *cityId;
    NSString *districtId;
//    if(self.addressDic)
//    {
//        //        proId = self.addressDic[@"provinceid"];
        //                cityId = self.addressDic[@"cityid"];
        //                districtId = self.addressDic[@"districtid"];
        //                    proId = [self.dataSource objectAtIndex:self.firstIndex][@"id"];
        //                    cityId = [self.cities objectAtIndex:self.secondIndex][@"id"];
        //                    districtId = [self.areas objectAtIndex:self.thirdIndex][@"id"];
        
//        if([self.addressLb.text isEqualToString:[NSString stringWithFormat:@"%@%@%@",self.addressDic[@"province"],self.addressDic[@"city"],self.addressDic[@"district"]]])//判断区域是否更改
//        {
//            proId = self.addressDic[@"provinceid"];
//            cityId = self.addressDic[@"cityid"];
//            districtId = self.addressDic[@"districtid"];
//        }else
//        {
//            proId = [self.dataSource objectAtIndex:self.firstIndex][@"id"];
//            cityId = [self.cities objectAtIndex:self.secondIndex][@"id"];
//            districtId = [self.areas objectAtIndex:self.thirdIndex][@"id"];
//        }
//    }else
//    {
//        proId = [self.dataSource objectAtIndex:self.firstIndex][@"id"];
//        cityId = [self.cities objectAtIndex:self.secondIndex][@"id"];
//        districtId = [self.areas objectAtIndex:self.thirdIndex][@"id"];
//    }
//    NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
//    NSDictionary *dic = @{@"consignee":self.nameTf.text,
//                          @"mobile":self.numTf.text,
//                          @"district":districtId,
//                          @"city":cityId,
//                          @"province":proId,
//                          @"user_id":userDic[USER_ID],
//                          @"address":self.DetailText.text,@"address_id":self.addressDic?self.addressDic[@"address_id"]:@""};
//    NSLog(@"...dic...%@",dic);
//    [self postWithURLString:@"/User/addAddress" parameters:dic success:^(id response) {
//        if(self.addressDic)[WToast showWithText:@"修改成功"];
//        else
//            [WToast showWithText:@"添加成功"];
//        NSLog(@"添加收货地址：%@",response);
//        //如果是编辑
//        if(self.addressDic)
//        {
//            // NSLog(@"传递过来的地址数据%@",self.addressDic);
//            //            NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:[XTool GetDefaultInfo:ADDRESS]];
//            //            [arr replaceObjectAtIndex:self.editIndex withObject:dic];
//            //   [XTool SaveDefaultInfo:arr Key:ADDRESS];
//            self.editSucess(dic);
//        }
//        else{
//            if([XTool GetDefaultInfo:ADDRESS])
//            {
//                NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:[XTool GetDefaultInfo:ADDRESS]];
//                [arr addObject:dic];
//                //   [XTool SaveDefaultInfo:arr Key:ADDRESS];
//
//            }
//            else{
//                NSMutableArray *arr = [NSMutableArray array];
//                [arr addObject:dic];
//                //    [XTool SaveDefaultInfo:arr Key:ADDRESS];
//
//            }
//            // self.addSucess(dic);
//        }
//        [self.navigationController popViewControllerAnimated:NO];
//    } failure:^(NSError *error) {
//
//    }];
    //    for(NSString *key in [dic allKeys])
    //    {
    //        NSLog(@"key....%@",key);
    //    }
    
}
@end
